package com.zhiqian.community.controller;

import com.zhiqian.community.entity.DiscussPost;
import com.zhiqian.community.entity.Page;
import com.zhiqian.community.entity.User;
import com.zhiqian.community.service.CommentService;
import com.zhiqian.community.service.DiscussPostService;
import com.zhiqian.community.service.LikeService;
import com.zhiqian.community.service.UserService;
import com.zhiqian.community.util.CommunityConstant;
import com.zhiqian.community.util.CommunityUtil;
import com.zhiqian.community.util.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {
    private static final Logger logger=LoggerFactory.getLogger(DiscussPostController.class);

    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;
    @Autowired
    private UserService userService;

    @PostMapping("/addOrUpdate")
    @ResponseBody
    public String addDiscussPost(DiscussPost discussPost){
        User user = hostHolder.getUser();
        boolean flag=discussPost.getId()!=null;
        if(flag){
            DiscussPost post = discussPostService.selectDiscussPostById(discussPost.getId());
            if (!post.getUserId().equals(user.getId())){
                return CommunityUtil.getJSONString(1,"权限不足");
            }
        }
        discussPost.setUserId(user.getId());
        discussPostService.insertDiscussPost(discussPost,flag);
        if (flag){
            return CommunityUtil.getJSONString(0,"修改成功！");
        }
        return CommunityUtil.getJSONString(0,"发布成功！");
    }

    @PostMapping("/draft")
    @ResponseBody
    public String addDraft(DiscussPost discussPost){
        User user = hostHolder.getUser();
        if (discussPost.getId()!=null){
            DiscussPost post = discussPostService.selectDiscussPostById(discussPost.getId());
            if (!post.getUserId().equals(user.getId())){
                return CommunityUtil.getJSONString(1,"权限不足！");
            }
        }
        discussPost.setUserId(user.getId());
        discussPostService.addDraft(discussPost);
        return CommunityUtil.getJSONString(0,"保存成功！");
    }

    @GetMapping("/toAdd")
    public String getMarkdownPage(Model model){
        DiscussPost draft = discussPostService.getDraft(hostHolder.getUser().getId());
        model.addAttribute("post",draft);
        return "/site/markdown";
    }

    @GetMapping("/toUpdate/{postId}")
    public String getMarkdownPageToo(@PathVariable("postId")Integer postId,Model model){
        DiscussPost post = discussPostService.selectDiscussPostById(postId);
        User user = hostHolder.getUser();
        if (!post.getUserId().equals(user.getId())){
            return "/error/404";
        }
        model.addAttribute("post",post);
        return "/site/markdown";
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer id, Model model, Page page){
        User user = hostHolder.getUser();
        Map<String, Object> map = discussPostService.selectDiscussPost(id);
        DiscussPost post = (DiscussPost) map.get("post");
        model.addAttribute("postVo",null);
        if (!post.getStatus().equals(DISCUSSPOST_STATUS_DELETE) && !post.getDraft().equals(DISCUSSPOST_DRAFT)) {
            int userStatus = user!=null?likeService.queryEntityLikeStatus(user.getId(), ENTITY_TYPE_POST, post.getId()):0;
            map.put("userStatus", userStatus);
            model.addAttribute("postVo", map);
            //查询评论
            page.setPath("/discuss/detail/" + id);
            page.setRows(post.getCommentCount());
            List<Map<String, Object>> comments = commentService.queryCommentsByEntity(ENTITY_TYPE_POST, id, page);
            model.addAttribute("comments", comments);
        }
        return "/site/discuss-detail";
    }

    /**
     * 查询用户发布的帖子
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @GetMapping("/user/{userId}")
    public String findDiscussPostIssuedByUser(@PathVariable("userId") Integer userId,Page page,Model model){
        User target = userService.getUserById(userId);
        if (target==null){
            logger.error("该用户不存在！");
            throw new RuntimeException("该用户不存在!");
        }
        page.setRows(discussPostService.findDiscussPostRows(userId));
        page.setLimit(20);
        page.setPath("/discuss/user/"+userId);
        List<Map<String, Object>> discussPosts = discussPostService.findDiscussPosts(userId, page,ORDER_MODE_NEW);
        model.addAttribute("discussPosts",discussPosts);
        model.addAttribute("target",target);
        return "/site/my-post";
    }

    /**
     * 置顶或取消置顶
     * @param postId
     * @return
     */
    @PostMapping("/stick/{postId}")
    @ResponseBody
    public String doStick(@PathVariable("postId")Integer postId){
        int rows = discussPostService.stickOrUnstick(postId,hostHolder.getUser().getId());
        if (rows == HANDLE_FAIL){
            return CommunityUtil.getJSONString(1,"操作失败");
        }
        return CommunityUtil.getJSONString(0,"修改成功！");
    }

    /**
     * 加精或取消加精
     * @param postId
     * @return
     */
    @PostMapping("/quintessence/{postId}")
    @ResponseBody
    public String quintessence(@PathVariable("postId")Integer postId){
        int rows = discussPostService.doQuintessence(postId);
        if (rows == HANDLE_FAIL){
            return CommunityUtil.getJSONString(1,"操作失败");
        }
        return CommunityUtil.getJSONString(0,"修改成功！");
    }

    @PostMapping("/delete/{postId}")
    @ResponseBody
    public String delete(@PathVariable("postId")Integer postId){
        User user = hostHolder.getUser();
        int rows = discussPostService.delete(postId, user);
        if (rows == HANDLE_FAIL){
            return CommunityUtil.getJSONString(1,"操作失败");
        }
        return CommunityUtil.getJSONString(0,"删除成功！");
    }
}
